/*******************************************************************************
* 自动化分析公式工具
*******************************************************************************/

KindEditor.plugin('autotool', function(K) {
	var self = this;
	var name = 'autotool';

	function combineRegex(keys) {
		return new RegExp(keys.join("|")
			.replace(/\]/g, "\\]").replace(/\[/g, "\\[")
			.replace(/\)/g, "\\)").replace(/\(/g, "\\("), "g");
	}


	self.clickToolbar(name, function() {

		var content = self.text();
		//函数
		if(window.dayhrFormula.ue_cf && window.dayhrFormula.ue_cf.length){
			window.dayhrFormula.ue_cf = window.dayhrFormula.ue_cf.sort(function(str1, str2) {
				return str2.length - str1.length
			});
			content = content.replace(combineRegex(window.dayhrFormula.ue_cf), function(match) {
				if(match.trim() == "")  return " ";
				return "<span style='color: " + window.dayhrFormula.colors.FUNC + ";'>" + match + "</span>";
			});
		}
		window.dayhrFormula.ue_ci = window.dayhrFormula.ue_ci.sort(function(str1, str2) {
			return str2.length - str1.length
		});
		content = content.replace(combineRegex(window.dayhrFormula.ue_ci), function(match, index, text) {
			if(match.trim() == "")  {
				return " ";
			}
			if(index > 0) {
				var c = text.charAt(index - 1);
				if(c && c != " " && c != "+" && c != "-" && c != "*" && c != "/" && c != "="
					&& c != ">" && c != "<" && c != "(" && c != "\"" && c != "," && c != "果"
					&& c != "么" && c != "滤" && c != "余" && c != "且" && c != "者" && c != "时"){
					return match;
				}
				c = text.charAt(index + match.length);
				if(c && c != " " && c != "+" && c != "-" && c != "*" && c != "/" && c != "="
					&& c != ">" && c != "<" && c != ")" && c != "\"" && c != "," && c != "如"
					&& c != "那" && c != "再" && c != "其" && c != "并" && c != "或" && c != "同"){
					return match;
				}
			}
			return "<span style='color: " + window.dayhrFormula.colors.ITEM + ";'>" + match + "</span>";
		});
		/*去掉有括号[]的这种*/
		/* content = content.replace(combineRegex(ue_cp), function(match) {
		 if(match.trim() == "")  return " ";
		 return "<span style='color: " + window.dayhrFormula.colors.PROP + ";'>" + match + "</span>";
		 });*/
		content = content.replace(combineRegex(window.dayhrFormula.ue_cl), function(match) {
			if(match.trim() == "")  return "";
			return "<span style='color: " + window.dayhrFormula.colors.LOGIC + ";'>&nbsp;" + match + "&nbsp;</span>";
		});
		self.html("<p>" + content + "</p>")
	});
});
